class NewslettersController < ApplicationController
  before_filter :login_required, :except => [:publish]
  layout 'default'
  
  # GET /newsletters
  def index
    @newsletters = Newsletter.find(:all)
  end

  # GET /newsletters/1
  def show
    @newsletter = Newsletter.find(params[:id])
    @contact = fake_contact
  end

  # GET /newsletters/new
  def new
    @newsletter = Newsletter.new
  end

  # GET /newsletters/1/edit
  def edit
    @newsletter = Newsletter.find(params[:id])
  end

  # POST /newsletters
  def create
    @newsletter = Newsletter.new(params[:newsletter])

    if @newsletter.save
      flash[:notice] = 'Newsletter was successfully created.'
      
      if params['add_section']
        @newsletter.newsletter_sections.create
        render :action => "edit"
      else
        redirect_to(@newsletter)
      end
    else
      render :action => "new"
    end
  end

  # PUT /newsletters/1
  def update
    @newsletter = Newsletter.find(params[:id])
    
    if @newsletter.update_attributes(params[:newsletter])
      flash[:notice] = 'Newsletter was successfully updated.'
      
      if params['add_section']
        @newsletter.newsletter_sections.create
        render :action => "edit"
      else 
        redirect_to(@newsletter)
      end
    else
      render :action => "edit"
    end
  end
  
 # GET /newsletters/1/publish
  def publish
    @newsletter = Newsletter.find_by_id(params[:id])
    if @newsletter.nil? or @newsletter.draft?
      render :text => 'The newsletter you chose has not been published.', :status => 404
    else
      @contact = fake_contact
    end
  end
  
  # PUT /newsletters/1/send_preview
  def send_preview
    @newsletter = Newsletter.find(params[:id])
    @contact = fake_contact(params[:email])
    MassEmail.deliver_newsletter(@contact, @newsletter, false)
    flash[:notice] = "Newsletter sent to #{@contact.email}."
    redirect_to(newsletter_url) 
  end

  # DELETE /newsletters/1
  def destroy
    @newsletter = Newsletter.find(params[:id])
    @newsletter.destroy

    redirect_to(newsletters_url)
  end
  
private
  def fake_contact(email = "example@email.com")
    Contact.new(:email => email, 
                :auth_token => 'sample')
  end
end
